package net.jarang.android.saleoffline.activity.sale;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import net.jarang.android.saleoffline.SaleContext;
import net.jarang.android.saleoffline.activity.AbstractAuthActivity;
import net.jarang.android.saleoffline.activity.MainActivity;
import net.jarang.android.saleoffline.activity.R;
import net.jarang.android.support.CanvasUtils;
import net.jarang.android.support.StringUtils;
import net.jarang.android.support.http.DefaultHttpInvocator;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class SaleRegisterActivity extends AbstractAuthActivity {
	private static final int PICK_FROM_CAMERA = 0;
	private static final int PICK_FROM_ALBUM = 1;
	private static final int CROP_FROM_CAMERA = 2;
	private static final int DATE_DIALOG_ID = 0;
	
	private SaleRegisterActivity thisContext;

	private EditText productNameET;
	private EditText shopNameET;
	private Uri takenPhotoUri, albumPhotoUri;
	private int pictureViewOrder = 1;
	private ImageView takePicture1IV, takePicture2IV;
	private Bitmap thumbnailImage1, thumbnailImage2;
	
	private EditText fromDateET, toDateET;
	private int iYear, iMonth, iDay;
	
	private View dateTempV;	//날짜 선택 후 값을 넣을 선택되어 있는 뷰 객체이다.
	
	private Spinner fromOffSN, toOffSN;
	
	@SuppressWarnings("rawtypes")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sale_register);
		
		productNameET = (EditText) findViewById(R.id.productNameET);
		shopNameET = (EditText) findViewById(R.id.shopNameET);
		
		fromOffSN = (Spinner) findViewById(R.id.fromOffSN);
		fromOffSN.setPrompt("세일 퍼센트를 고르세요.");
		ArrayAdapter adapter1 = ArrayAdapter.createFromResource(this, R.array.sale_off, android.R.layout.simple_spinner_item);
		adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		fromOffSN.setAdapter(adapter1);
		fromOffSN.setOnItemSelectedListener(fromOffSNOnItemSelectedListener);
		
		toOffSN = (Spinner) findViewById(R.id.toOffSN);
		toOffSN.setPrompt("세일 퍼센트를 고르세요.");
		ArrayAdapter adapter2 = ArrayAdapter.createFromResource(this, R.array.sale_off, android.R.layout.simple_spinner_item);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		toOffSN.setAdapter(adapter2);
		fromOffSN.setOnItemSelectedListener(toOffSNOnItemSelectedListener);
		
		takePicture1IV = (ImageView)findViewById(R.id.takePicture1IV);
		takePicture2IV = (ImageView)findViewById(R.id.takePicture2IV);

		thisContext = this;
		
		// 세일 날짜
		final Calendar objTime = Calendar.getInstance();
		iYear = objTime.get(Calendar.YEAR);
		iMonth = objTime.get(Calendar.MONTH);
		iDay = objTime.get(Calendar.DAY_OF_MONTH);

		fromDateET = (EditText)findViewById(R.id.fromDateET);
    	toDateET = (EditText)findViewById(R.id.toDateET);
		fromDateET.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dateTempV = v;
				showDialog(DATE_DIALOG_ID);
			}
		});
		toDateET.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dateTempV = v;
				showDialog(DATE_DIALOG_ID);
			}
		});
	}
	
	public void onClickSave(View v) {
		String url = "http://jarang.iptime.org:8080/sale/insert.json";
		
		FileOutputStream fos1 = null;
		FileOutputStream fos2 = null;
		File file1 = null;
		File file2 = null;
		
		try {
			if (thumbnailImage1 != null) {
				fos1 = new FileOutputStream("/sdcard/saleoffline_thumbnail1.jpg");
				thumbnailImage1.compress(CompressFormat.JPEG, 100, fos1);
				file1 = new File("/sdcard/saleoffline_thumbnail1.jpg");
			}
			if (thumbnailImage2 != null) {
				fos2 = new FileOutputStream("/sdcard/saleoffline_thumbnail2.jpg");
				thumbnailImage2.compress(CompressFormat.JPEG, 100, fos2);
				file2 = new File("/sdcard/saleoffline_thumbnail2.jpg");
			}
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("productName", productNameET.getText() + "");
			params.put("writerId", ((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number());
			params.put("writerName", "자랑넷");
			params.put("saleDateFrom", fromDateET.getText());
			params.put("saleDateTo", toDateET.getText());
			params.put("saleOffFrom", StringUtils.substringForLast((String)fromOffSN.getSelectedItem(), -1));
			params.put("saleOffTo", StringUtils.substringForLast((String)toOffSN.getSelectedItem(), -1));
			params.put("shopName", shopNameET.getText() + "");		
			params.put("photos", file1);
			params.put("photos", file2);

			DefaultHttpInvocator httpInvocator = new DefaultHttpInvocator();
			httpInvocator.post(url, params, null);
		} catch (Exception e) {
			Log.e(SaleContext.TAG, e.getMessage(), e);
		}
		Toast.makeText(this, "저장되었습니다.", Toast.LENGTH_SHORT).show();
		
		finish();
		Intent intent = new Intent(thisContext, SaleListActivity.class);
		startActivity(intent);
	}
	
	private OnItemSelectedListener fromOffSNOnItemSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}
	};	
	
	private OnItemSelectedListener toOffSNOnItemSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		}
		
		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}
	};	
	
    @Override
    protected Dialog onCreateDialog(int id) {
    	switch(id) {
          case DATE_DIALOG_ID:
                 return new DatePickerDialog(this, mDateSetListener, iYear, iMonth, iDay);
    	}
          return null;
    }

    private void updateDisplay(EditText et) {
          et.setText(new StringBuilder().append(iYear).append("-")
                 .append(iMonth + 1).append("-").append(iDay));
    }

    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {                 
    	public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    		iYear = year;
    		iMonth = monthOfYear;
    		iDay = dayOfMonth;

    		if(dateTempV.getId() == R.id.fromDateET) {
    			updateDisplay(fromDateET);
    		} else {
    			updateDisplay(toDateET);
    		}
    	}
    };	
	
	/**
	 * 카메라에서 이미지 가져오기
	 */
	private void doTakePhotoAction() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		// 임시로 사용할 파일의 경로를 생성
		String fileName = "tmp_" + String.valueOf(System.currentTimeMillis()) + ".jpg";
		takenPhotoUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), fileName));

		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, takenPhotoUri);
		// intent.putExtra("return-data", true); 특정기기에서 사진을 저장못하는 문제가 있어 다음을 주석처리
		startActivityForResult(intent, PICK_FROM_CAMERA);
	}

	/**
	 * 앨범에서 이미지 가져오기
	 */
	private void doTakeAlbumAction() {
		// 앨범 호출
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
		startActivityForResult(intent, PICK_FROM_ALBUM);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}

		switch (requestCode) {
			case PICK_FROM_ALBUM: {
				albumPhotoUri = data.getData();
				doCrop(albumPhotoUri);
				break;
			}
	
			case PICK_FROM_CAMERA: {
				doCrop(takenPhotoUri);
				break;
			}
			case CROP_FROM_CAMERA: {
				final Bundle extras = data.getExtras();
	
				if (extras != null) {
					if (pictureViewOrder == 1) {
						thumbnailImage1 = extras.getParcelable("data");
						takePicture1IV.setImageBitmap(CanvasUtils.getRoundedCornerBitmap(thumbnailImage1));
					} else {
						thumbnailImage2 = extras.getParcelable("data");
						takePicture2IV.setImageBitmap(CanvasUtils.getRoundedCornerBitmap(thumbnailImage2));
					}
				}
				break;
			}			
		}
	}

	private void doCrop(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("outputX", 135);
		intent.putExtra("outputY", 105);
		intent.putExtra("aspectX", 9);
		intent.putExtra("aspectY", 7);
		intent.putExtra("scale", true);
		intent.putExtra("return-data", true);
		
		startActivityForResult(intent, CROP_FROM_CAMERA);
		
		//임시파일 삭제
		if (takenPhotoUri != null) {
			File f = new File(takenPhotoUri.getPath());
			if (f.exists()) {
				f.delete();
			}
		}
	}

	public void onClickFirstImageView(View v) {
		pictureViewOrder = 1;
		onClickImageView(v);
	}
	
	public void onClickSecondImageView(View v) {
		pictureViewOrder = 2;
		onClickImageView(v);
	}
	
	public void onClickImageView(View v) {
		DialogInterface.OnClickListener cameraListener = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				doTakePhotoAction();
			}
		};
		
		DialogInterface.OnClickListener albumListener = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				doTakeAlbumAction();
			}
		};
		
		new AlertDialog.Builder(this).setTitle("업로드할 이미지 선택").setPositiveButton("사진촬영", cameraListener)
		.setNeutralButton("앨범선택", albumListener).show();
	}
	
	@Override
	public void onBackPressed() {
    	new AlertDialog.Builder(this)
    	.setTitle("세일상품 등록 취소")
    	.setMessage("등록을 취소하시겠습니까?")
    	.setIcon(R.drawable.icon)
    	.setPositiveButton("예", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface dialog, int whichButton) {
    			finish();
    			Intent intent = new Intent(thisContext, MainActivity.class);
    			startActivity(intent);
    		}
    	})
    	.setCancelable(false)
    	.setNegativeButton("아니요", null)
    	.show();
    }
}
